package com.bookmall.cart.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.bookmall.cart.domain.Cart;
import com.bookmall.cart.domain.CartItem;
import com.bookmall.cart.domain.vo.BookInfoVo;
import com.bookmall.cart.feign.ProductFeignService;
import com.bookmall.cart.interceptor.CartInterceptor;
import com.bookmall.cart.service.ICartService;
import com.bookmall.common.constant.ExceptionTypeConstants;
import com.bookmall.common.entity.to.MemberInfoTo;
import com.bookmall.common.exception.LogOutException;
import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.web.domain.AjaxResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description:
 * @Author 胡菜鸡
 * @Create 2022-04-15-14:11
 */
@Slf4j
@Service
public class CartServiceImpl implements ICartService {
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private ProductFeignService productFeignService;

    /** 购物车前缀 */
    private final String CART_PREFIX = "bookmall:cart";

    /**
     * 添加书籍至购物车
     * @author 胡菜鸡
     * @date 2022/4/19 15:17
     */
    @Override
    public CartItem addToCart(String bookId, Integer count) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        //获取redis中的数据
        String res = (String) cartOps.get(bookId);
        if(StringUtils.isBlank(res)){
            //购物车无此商品

            //1、远程查询书籍信息
            String json = productFeignService.bookItem(bookId);
            BookInfoVo bookInfoVo = JSON.parseObject(json, BookInfoVo.class);
            //2、添加商品项信息到购物车
            CartItem cartItem = new CartItem();
            cartItem.setId(bookInfoVo.getId());
            cartItem.setName(bookInfoVo.getBookName());
            cartItem.setCategoryId(bookInfoVo.getBookType());
            cartItem.setCategoryName(bookInfoVo.getBookTypeName());
            cartItem.setPrice(bookInfoVo.getBookPrice());
            cartItem.setCount(count);
            cartItem.setImage(bookInfoVo.getImagesArray()[0]);
            cartItem.setCheck(true);

            cartOps.put(bookId, JSON.toJSONString(cartItem));
            return cartItem;
        } else {
            //购物车有此商品 -> 修改购物车中的商品数量
            CartItem cartItem = JSON.parseObject(res, CartItem.class);
            cartItem.setCount(cartItem.getCount()+count);
            cartOps.put(bookId, JSON.toJSONString(cartItem));
            return cartItem;
        }
    }

    /**
     * 获取购物车中的购物项
     * @author 胡菜鸡
     * @date 2022/4/19 17:58
     */
    @Override
    public CartItem getCartItem(String bookId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        String str = (String) cartOps.get(bookId);
        CartItem cartItem = JSON.parseObject(str, CartItem.class);
        return cartItem;
    }



    /**
     * 获取一个购物车
     * @author 胡菜鸡
     * @date 2022/4/19 21:56
     */
    @Override
    public Cart getCart() {
        MemberInfoTo memberInfoTo = CartInterceptor.threadLocal.get();
        Cart cart = new Cart();
        if(memberInfoTo != null){
            //登录状态
            String cartKey = CART_PREFIX + memberInfoTo.getId();
            // 获取登录后的购物车数据
            List<CartItem> cartItems = getCartItems(cartKey);
            cart.setItems(cartItems);
            return cart;
        } else {
            //还没有登录
            throw new LogOutException("用户未登录", ExceptionTypeConstants.USER_LOGOUT);
        }
    }

    /**
     * 获取redis连接
     * @author 胡菜鸡
     * @date 2022/4/19 17:41
     */
    private BoundHashOperations<String, Object, Object> getCartOps() {
        MemberInfoTo memberInfoTo = CartInterceptor.threadLocal.get();

        String cartKey = "";
        if(memberInfoTo != null){
            //用户已经登录
            cartKey = CART_PREFIX + memberInfoTo.getId();
        } else {
            throw new LogOutException("用户未登录", ExceptionTypeConstants.USER_LOGOUT);
        }

        //绑定接下来的操作都是对 cartKey 的操作
        return redisTemplate.boundHashOps(cartKey);
    }

    /**
     * 获取购物车中的所有购物项
     * @author 胡菜鸡
     * @date 2022/4/19 22:12
     */
    private List<CartItem> getCartItems(String cartKey){
        BoundHashOperations<String, Object, Object> hashOps = redisTemplate.boundHashOps(cartKey);
        List<Object> values = hashOps.values();
        if(values != null && values.size() > 0){
            List<CartItem> cartItemList = values.stream().map(obj -> {
                String str = (String) obj;
                CartItem cartItem = JSON.parseObject(str, CartItem.class);
                return cartItem;
            }).collect(Collectors.toList());
            return cartItemList;
        }
        return null;
    }

    /**
     * 清空购物车
     * @author 胡菜鸡
     * @date 2022/4/19 22:16
     */
    @Override
    public Boolean clearCart(String cartKey){
        return redisTemplate.delete(cartKey);
    }

    /**
     * 勾选购物项
     * @author 胡菜鸡
     * @date 2022/4/20 8:57
     */
    @Override
    public CartItem checkItem(String bookId, Integer check) {
        CartItem cartItem = getCartItem(bookId);
        cartItem.setCheck(check==1?true:false);

        String str = JSON.toJSONString(cartItem);
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.put(bookId, str);
        return cartItem;
    }

    /**
     * 改变购物项数量
     * @author 胡菜鸡
     * @date 2022/4/20 10:02
     */
    @Override
    public CartItem countItem(String bookId, Integer count) {
        CartItem cartItem = getCartItem(bookId);
        cartItem.setCount(count);

        String str = JSON.toJSONString(cartItem);
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.put(bookId, str);
        return cartItem;
    }

    /**
     * 删除购物车商品项
     * @author 胡菜鸡
     * @date 2022/4/20 10:58
     */
    @Override
    public Long deleteItem(String bookId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        return cartOps.delete(bookId);
    }

    /**
     * 获取用户购物车中的数据
     * @author 胡菜鸡
     * @date 2022/4/21 18:01
     */
    @Override
    public List<CartItem> getUserCartItems() {
        MemberInfoTo memberInfoTo = CartInterceptor.threadLocal.get();
        if(memberInfoTo == null){
            return null;
        }
        //获取所有被选中的购物项
        String cartKey = CART_PREFIX + memberInfoTo.getId();
        List<CartItem> cartItems = getCartItems(cartKey);
        if(cartItems == null){
            return null;
        }
        List<CartItem> collect = cartItems.stream()
                .filter(cartItem -> cartItem.isCheck())
                .map(cartItem -> {
                    //更新最新价格
                    AjaxResult ajaxResult = productFeignService.getInfo(cartItem.getId());
                    BookInfoVo bookInfoVo = ajaxResult.getData("data", new TypeReference<BookInfoVo>() {});
                    if(bookInfoVo == null){
                        throw new ServiceException("该商品已被移除");
                    }
                    cartItem.setPrice(bookInfoVo.getBookPrice());
                    //更新库存
                    cartItem.setStock(bookInfoVo.getBookCount()-bookInfoVo.getCountStockLocked());
                    return cartItem;
                }).collect(Collectors.toList());

        return collect;
    }

    /**
     * 获取购物车中登录会员的购物项数据
     * @author 胡菜鸡
     * @date 2022/4/28 17:36
     */
    @Override
    public Cart getCartInfoByLoginMember() {
        MemberInfoTo memberInfoTo = CartInterceptor.threadLocal.get();
        if(memberInfoTo == null){
            //没有登录，返回空购物车
            return null;
        }
        Cart cart = getCart();
        if(cart.getItems() == null){
            cart.setItems(new ArrayList<>());
        }
        return cart;
    }
}
